<?php
namespace app\channel\controller\sys_admin;
use app\AdminController;
use think\Db;
use app\channel\model\ProxyUpapplyLogModel;
use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUsersModel;
use app\channel\model\RechargeLogModel;
use app\mainadmin\model\SettingsModel;
use app\channel\model\RewardLogModel;
/**
 * 升级申请
 * Class Index
 * @package app\store\controller
 */
class UpCheck extends AdminController
{
	/*------------------------------------------------------ */
	//-- 优先执行
	/*------------------------------------------------------ */
	public function initialize(){
        parent::initialize();
        $this->Model = new ProxyUpapplyLogModel();
    }
	/*------------------------------------------------------ */
	//-- 主页
	/*------------------------------------------------------ */
    public function index(){
        $this->assign("start_date", date('Y/m/01', strtotime("-1 year")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);
		return $this->fetch();
	}
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false) {

        $search['reward_type'] = input('reward_type','','trim');
        $search['status'] = input('status',-1,'intval');
        $search['type'] = input('type',0,'intval');
        $search['proxy_id'] = input('proxy_id',0,'intval');
        $search['up_proxy_id'] = input('up_proxy_id',0,'intval');
        $reportrange = input('reportrange');
        $where = [];
        if (empty($search['reward_type']) == false){
            $where[] = ['reward_type','=',$search['reward_type']];
        }
        if (empty($reportrange) == false){
            $dtime = explode('-',$reportrange);
            $where[] = ['add_time','between',[strtotime($dtime[0]),strtotime($dtime[1])+86399]];
        }else{
            $where[] = ['add_time','between',[strtotime("-1 year"),time()]];
        }
        if ($search['status'] >= 0){
            $where[] = ['status','=',$search['status']];
        }
        if ($search['type']>0) {
            $where[] = ['type','=',$search['type']];
        }
        if ($search['proxy_id'] > 0){
            $where[] = ['proxy_id','=',$search['now_proxy_id']];
        }
        if ($search['up_proxy_id'] > 0){
            $where[] = ['up_proxy_id','=',$search['up_proxy_id']];
        }
        if (empty($search['keyword']) == false){
            $UsersModel = new UsersModel();
            $uids = $UsersModel->where(" mobile LIKE '%".$search['keyword']."%' OR user_id = '".$search['keyword']."'")->column('user_id');
            $uids[] = -1;//增加这个为了以上查询为空时，限制本次主查询失效
            $where[] = ['user_id','in',$uids];
        }
        $data = $this->getPageList($this->Model,$where);
        $ProxyLevelList =  (new ProxyLevelModel)->getList();
        $ProxyUsersModel = new ProxyUsersModel();
        foreach ($data['list'] as $key=>$row){
            if ($row['new_supply_uid'] == 0 && $row['check_time'] == 0){
                $row['new_supply_uid'] = $ProxyUsersModel->getSupplyUid($row['user_id'],$row['up_proxy_id'],$ProxyLevelList);
            }
            $data['list'][$key] = $row;
        }
        $this->assign("proxyLevel",$ProxyLevelList);
        $this->assign("search", $search);
        $this->assign("status", $this->Model->status);
        $this->assign("type_list", $this->Model->type_list);
        $this->assign("data", $data);
        if ($runData == false){
            $data['content']= $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 详情
    /*------------------------------------------------------ */
    public function info() {
        $log_id = input('log_id',0,'intval');
        if ($log_id < 1){
            return $this->error('传参错误.');
        }
        $row = $this->Model->where('log_id',$log_id)->find();
        if (empty($row)){
            return $this->error('没有找到相关记录.');
        }
        $ProxyLevelList =  (new ProxyLevelModel)->getList();
        $row['new_supply_uid'] = (new ProxyUsersModel)->getSupplyUid($row['user_id'],$row['up_proxy_id'],$ProxyLevelList);
        $row['userinfo'] = (new ProxyUsersModel)->info($row['user_id']);
        $row['newuserinfo'] = (new ProxyUsersModel)->info($row['pid']);
        $this->assign('row',$row->toArray());
        $this->assign('status',$this->Model->status);
        $this->assign("proxyLevel", $ProxyLevelList);
        return $this->fetch('info');
    }

    /*------------------------------------------------------ */
    //-- 审核
    /*------------------------------------------------------ */
    public function check() {
        $log_id = input('log_id',0,'intval');
        if ($log_id < 1){
            return $this->error('传参错误.');
        }
        $operating = input('operating','','trim');
        $admin_note = input('admin_note','','trim');
        $upData['check_time'] = time();
        $upData['check_uid'] = AUID;
        $upData['admin_note'] = $admin_note;
        if ($operating == 'refuse'){
            if (empty($admin_note) == true){
                return $this->error('请填写操作备注.');
            }
            $upData['status'] = 1;
            $res = $this->Model->where('log_id',$log_id)->update($upData);
            if ($res < 1){
                return $this->error('更新审核结果失败.');
            }
            return $this->success('操作成功.');
        }
        $row = $this->Model->where('log_id',$log_id)->find();
        if (empty($row)){
            return $this->error('没有找到相关记录.');
        }
        $upData['status'] = 9;
        $ProxyLevelList =  (new ProxyLevelModel)->getList();
        $ProxyUsersModel = new ProxyUsersModel();
        $new_supply_uid = $ProxyUsersModel->getSupplyUid($row['user_id'],$row['up_proxy_id'],$ProxyLevelList);
        Db::startTrans();//开启事务
        $upData['new_supply_uid'] = $new_supply_uid;
        $res = $this->Model->where('log_id',$log_id)->update($upData);
        if ($res < 1){
            Db::rollback();//回滚事务
            return $this->error('更新审核结果失败.');
        }
        $res = $ProxyUsersModel->upgrade($row['user_id'],$row['up_proxy_id'],'升级申请审核.',$this);
        if ($res !== true){
            Db::rollback();//回滚事务
            return $this->error($res);
        }
        $orderinfo = (new RechargeLogModel)->where(['order_id'=>$row['order_id']])->find();
        if ($row['type']==2&&$row['order_id']>0&&$orderinfo) {
            if ($this->upapplyCheck($row['order_id'],1,$row['up_proxy_id'])==2) {
                Db::rollback();//回滚事务
                return $this->error('更新保证金奖励失败.');
            }
        }
        Db::commit();//提交事务
        return $this->success('操作成功.');
    }

    /*------------------------------------------------------ */
    //-- 处理上级保证金奖励
    /*------------------------------------------------------ */
    public function upapplyCheck($order_id ,$type=1,$up_proxy_id=0) {
        $orderModel = new RechargeLogModel();
        $userModel = new ProxyUsersModel();
        if ($order_id<=0) {
            return 0;
        }
        // 订单信息
        $order = $orderModel->where(['order_id'=>$order_id,'upgrade_type'=>2,'order_type'=>1])->find();
        if (!$order) {
            return 0;
        }
        // 奖励百分比信息
        $settingModel = new SettingsModel();
        $up_setting = $settingModel->where('name','bzjsjjl')->find();
        $up_setting = json_decode($up_setting['data'],true);
        $touserinfo = $userModel->info($order['user_id']);
        switch ($type) {
            case 1:
                $userinfo = $userModel->where('user_id',$order['user_pid'])->find();
                if (!$userinfo) {
                    return 1;
                }
                if ($this->addOrder((float)$order['order_amount']*(float)$up_setting['up_number']/100,$userinfo['user_id'],$userinfo['pid'],$userinfo['proxy_id'],$touserinfo['user_id'],$touserinfo['proxy_id'],$touserinfo['byUser']['nick_name'],$order_id,$up_proxy_id)) {
//                    return $this->upapplyCheck($order_id,2);
                    return 1;
                } else {
                    Db::rollback();//回滚事务
                    return 2;
                }
                break;
            case 2:
                $userinfo = $userModel->where('user_id',$order['user_pid'])->find();
                $userinfo = $userModel->where('user_id',$userinfo['pid'])->find();
                if (!$userinfo) {
                    return 1;
                }
                if ($this->addOrder((float)$order['order_amount']*(float)$up_setting['up_number']/100*(float)$up_setting['up_up_number']/100,$userinfo['user_id'],$userinfo['pid'],$userinfo['proxy_id'],$touserinfo['user_id'],$touserinfo['proxy_id'],$touserinfo['byUser']['nick_name'],$order_id,$up_proxy_id)) {
                    return 1;
                } else {
                    Db::rollback();//回滚事务
                    return 2;
                }
                return 0;
                break;
        }
        return 0;

    }

    /*------------------------------------------------------ */
    //-- 添加奖励订单
    /*------------------------------------------------------ */
    public function addOrder($replenish_money,$user_id,$pid,$proxy_id,$user_id1=0,$user_proxy_id=0,$username="",$order_id,$up_proxy_id) {
        $orderModel = new RechargeLogModel();
        $RewardLogModel = new RewardLogModel();
        $save_data = [
            'type'=>'earnestMoney','user_id'=>$user_id,'user_pid'=>$pid,'order_sn'=>'bzjupapply'.time().rand(11,99),'order_amount'=>$replenish_money,'transaction_id'=>'','pay_id'=>3,'pay_code'=>'offline','pay_name'=>'线下打款','imgs'=>'','remark'=>'',
            'status'=>0,'check_remark'=>'','add_time'=>time(),'pay_time'=>time(),'check_time'=>0,'admin_id'=>0,'is_reward'=>0,'supply_uid'=>0,'proxy_id'=>$proxy_id,'upgrade_type'=>1,'order_type'=>2
        ];
        $userProxyModel = new ProxyLevelModel();
        $proxyInfo = $userProxyModel->info($user_proxy_id,true);

        $levelList = $this->getList();
        $proxy = $levelList[$proxy_id];//当前层级
        if($proxy_id <= 0){
            $proxy['level'] = 99;
        }
        // 奖励百分比信息
        $settingModel = new SettingsModel();
        $up_setting = $settingModel->where('name','bzjsjjl')->find();
        $up_setting = json_decode($up_setting['data'],true);
        $rows = array_reverse($levelList);//反转数组
        foreach ($rows as $k=>$v) {
            $proxy = $levelList[$proxy_id];
            if ($v['level'] == $proxy['level']) {
                if ($replenish_money>$v['replenish_money']*(float)$up_setting['up_number']/100) {
                    $replenish_money = $v['replenish_money']*(float)$up_setting['up_number']/100;
                }
            }
        }
        if ($up_proxy_id!=$proxy_id) {
            return false;
        }
        $userModel = new ProxyUsersModel();
        $userinfo = $userModel->info($user_id);
        $orderinfo = (new RechargeLogModel)->where(['order_id'=>$order_id])->find();
        $userProxyModel = new ProxyLevelModel();
        $uppidname = $userProxyModel->info($orderinfo['up_proxy_id'],true);
        $pidname = $userProxyModel->info($orderinfo['proxy_id'],true);
        if ($userinfo['contract_time']>strtotime("-1 year")) {
            $add_data = [
                'reward_type' => 'bzjsjjl', 'reward_name' => '保证金升级奖励', 'reward_money' => $replenish_money, 'to_uid' => $user_id, 'to_proxy_id' => $proxy_id, 'from_uid' => $user_id1, 'payer_uid' => $user_id1,
                'from_proxy_id' => $user_proxy_id, 'form_type' => 'recharge', 'from_id' => $order_id, 'status' => 1, 'add_time' => time(), 'update_time' => time(), 'reward_info' => "用户【{$username}】通过保证金升级为{$proxyInfo}", 'is_log' => 0
            ];
            bondLog($orderinfo['user_id'],$orderinfo['order_id'],$orderinfo['pid'],1,2,$orderinfo['order_amount'],$content="{$pidname}升级为{$uppidname}");
        } else {
            $add_data = [
                'reward_type' => 'bzjsjjl', 'reward_name' => '保证金升级奖励', 'reward_money' => $replenish_money, 'to_uid' => $user_id, 'to_proxy_id' => $proxy_id, 'from_uid' => $user_id1, 'payer_uid' => $user_id1,
                'from_proxy_id' => $user_proxy_id, 'form_type' => 'recharge', 'from_id' => $order_id, 'status' => 0, 'add_time' => time(), 'update_time' => time(), 'reward_info' => "用户【{$username}】通过保证金升级为{$proxyInfo}", 'is_log' => 0
            ];
            bondLog($orderinfo['user_id'],$orderinfo['order_id'],$orderinfo['pid'],1,1,$orderinfo['order_amount'],$content="合同到期，无法返还保证金");
        }
        if($RewardLogModel->save($add_data)) {
            return true;
        } else {
            return false;
        }
    }

}
